import { _decorator, Component, Node, Label } from 'cc';
import { BaseView } from '../../../../../scripts/libs/rxjs/cc3/BaseView';
import { ReactiveProperty } from '../../../../../scripts/libs/rxjs/cc3/ReactiveProperty';
import { Observable } from 'rxjs';
import { AnimationPlay, AnimationPlayWithEvent } from '../../../../../scripts/libs/rxjs/cc3/AnimationPlay';
import { Animation } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PipeView')
export class PipeView extends BaseView {

    posId: number = null;
    pipeId: number = null;

    animating = ReactiveProperty.Create(false);

    colorList = ReactiveProperty.Create<number[]>([]);

    @property(Label)
    countLabel: Label = null;

    useObserves() {
        return [
            this.colorList.subscribe(this.refresh.bind(this)),
        ];
    }

    refresh() {
        this.countLabel.string = `${this.colorList.value.length}`;
        // if (this.colorList.value.length > 0) {
        //     this.countLabel.node.active = true;
        // } else {
        //     this.countLabel.node.active = false;
        // }
    }

    reset() {
        this.animating.value = false;
        this.colorList.value.splice(0, this.colorList.value.length);
    }

    canBurst() {
        return this.colorList.value.length > 0;
    }

    burstBlock(): Observable<number> {
        return new Observable(observer => {
            this.animating.value = true;
            let _sub = AnimationPlayWithEvent(this.getComponent(Animation), 'PipeBurst').subscribe({
                next: _ => {
                    if (_.state == 'event' && _.eventName == 'burst') {
                        let colorId = this.colorList.value.shift();
                        this.colorList.again();
                        this.animating.value = false;
                        observer.next(colorId);
                    }
                },
                complete: () => {
                    observer.complete();
                }
            });
            return () => {
                if (_sub) {
                    _sub.unsubscribe();
                    _sub = null;
                }
            }
        });
    }

}

